<template>
    <el-tabs v-model="activeName">
        <el-tab-pane name="first">
            <span slot="label"><i class="el-icon-date"></i>广告管理</span>
            <el-table
                    ref="multipleTable"
                    :data="adList"
                    tooltip-effect="dark"
                    style="width: 100%"
                    @selection-change="handleSelectionChange">
                <el-table-column
                        type="selection"
                        width="55">
                </el-table-column>
<!--                广告名称-->
                <el-table-column
                        prop="adName"
                        label="广告名称"
                        width="200">
                </el-table-column>
                <el-table-column
                        prop="adImg"
                        label="广告图片"
                        width="200">
                    <template slot-scope="scope">
                        <img  :src="`http://172.17.4.241:8887/upload`+ scope.row.adImg" alt="" style="width: 120px;height: 60px">
                    </template>
                </el-table-column>
                <el-table-column
                    label="开始日期"
                    show-overflow-tooltip>
                    2021/02/03
            </el-table-column>
                <el-table-column
                      prop="startTime"
                        label="结束日期"
                        show-overflow-tooltip>
                    2021/05/20
                </el-table-column>

                <el-table-column
                        prop="adStatus"
                        label="显示"
                        show-overflow-tooltip>
                    <template slot-scope="scope">
                            <el-switch
                                    v-model="scope.row.adStatus"
                                    active-color="#13ce66"
                                    inactive-color="#f3f3f3"
                                    :active-value= 0
                                    :inactive-value= 1
                                    @change="status(scope.row)">
                            </el-switch>
                    </template>
                </el-table-column>
                <el-table-column
                        fixed="right"
                        label="操作"
                        width="100">
                    <template slot-scope="scope">
                        <el-button @click="handleClick(scope.row)" type="primary" icon="el-icon-edit" circle size="small"></el-button>
                        <el-button
                                @click.native.prevent="deleteRow(scope.row.adId, adList)"
                                type="danger" icon="el-icon-delete" circle
                                size="small"
                                style="border-color: #f2f2f2;background-color: #f2f2f2">
                        </el-button><!--将单选的id传到后台-->
                    </template>
                </el-table-column>
            </el-table>
            <div style="margin-top: 20px">
                <el-button @click="toggleSelection" class="delete">删除</el-button>
            </div>
            <div class="block">
                <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="currentPage1"
                        :page-size="pageNum"
                        layout="total, prev, pager, next, jumper"
                        :total="total" style="text-align: right">

                </el-pagination>
            </div>
        </el-tab-pane>
<!--        =========================================新增=============================================================-->
        <el-tab-pane name="second" label="新增广告">
                <el-form :model="addAdArr" :rules="rules" ref="addAdArr" label-width="100px" class="demo-addAdArr">
                    <el-form-item label="广告名称" prop="ad_name">
                        <el-input v-model="addAdArr.adName"  placeholder="请输入想添加的广告商品名称" @blur="getGoodsId"></el-input>
                    </el-form-item>
                    <!--开始日期和结束日期-->
                    <el-form-item label="活动日期">
                        <el-col :span="11">
                            <el-form-item prop="adCreateTime">
                                <el-date-picker type="date" placeholder="选择开始日期" v-model="addAdArr.ad_create_time" style="width: 100%;"></el-date-picker>
                            </el-form-item>
                        </el-col>
                        <!--结束日期-->
                        <el-col :span="11">
                            <el-form-item prop="adUpdateTime">
                                <el-date-picker type="date" placeholder="选择结束日期" v-model="addAdArr.ad_update_time" style="width: 100%;"></el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-form-item>

                    <el-form-item label="广告url" prop="adUrl">
                        <el-select v-model="addAdArr.adUrl" placeholder="请选择" @blur="console">
                            <el-option
                                    v-for="item in zhi"
                                    :key="item.goodsId"
                                    :label="item.goodsId"
                                    :value="item.goodsId">
                            </el-option>
                        </el-select>
<!--                        <el-input v-model="addAdArr.adUrl" disabled></el-input>-->
                    </el-form-item>
                    <el-form-item label="广告图片" prop="file" multiple="false" v-model="addAdArr.file">
                        <el-upload
                                ref="pictureUpload"
                                :file-list="fileList"
                                :on-change="handleChange"
                                :limit="1"
                                action="#"
                                list-type="picture-card"
                                :http-request="uploadFile"
                                :auto-upload="false">
                            <i slot="default" class="el-icon-plus"></i>
                            <div slot="file" slot-scope="{file}">
                                <img
                                        class="el-upload-list__item-thumbnail"
                                        :src="addAdArr.file=file.url" alt=""
                                >
                                <span class="el-upload-list__item-actions">
        <span
                class="el-upload-list__item-preview"
                @click="handlePictureCardPreview(file)"
        >
          <i class="el-icon-zoom-in"></i>
        </span>
        <span
                v-if="!disabled"
                class="el-upload-list__item-delete"
                @click="handleDownload(file)"
        >
          <i class="el-icon-download"></i>
        </span>
        <span
                v-if="!disabled"
                class="el-upload-list__item-delete"
                @click="handleRemove(file)"
        >
          <i class="el-icon-delete"></i>
        </span>
      </span>
                            </div>
                        </el-upload>
                        <el-dialog :visible.sync="dialogVisible">
                            <img width="100%" :src="addAdArr.file" alt="">
                        </el-dialog>
                    </el-form-item>
                    <el-form-item label="是否显示" prop="resource">
                        <el-radio-group v-model="addAdArr.adStatus">
                            <el-radio v-model="addAdArr.adStatus" label="0">开启</el-radio>
                            <el-radio v-model="addAdArr.adStatus" label="1">关闭</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="submitForm('addAdArr')">立即创建</el-button>
                        <el-button @click="resetForm('addAdArr')">重置</el-button>
                    </el-form-item>
                </el-form>
        </el-tab-pane>
    </el-tabs>
</template>

<script>
    export default {
        name: "advertisement",
        methods: {
            console(){
              console.log(this.addAdArr)
            },
            //分页
            //分页每页几条
            handleSizeChange(val) {
                this.pageNum = val
                console.log(`每页 ${val} 条`);
            },
            //修改显示状态
            status(data) {

                this.$axios({
                    method: 'post',
                    url: '/api/ad/edit',
                    params: {adId: data.adId, adName: data.adName, adUrl: data.adUrl, adStatus: data.adStatus},

                }).then((res) => {
                    console.log(res)
                }).catch((err) => {
                    console.log(err)
                })
            },
            //请求点击的当前页 当前页数据
            handleCurrentChange(val) {
                this.currentPage1 = val
                this.$axios.post('/api/ad/adlist?page=' + val).then((res) => {
                    this.adList = res.data.data
                    //分页
                    this.total = res.data.count
                })
                // this.currentChangePage(this.adList,val);//获取用户点击的当前页后刷新数据
                // this.$axios.post('/api/articleList',{page:val}).then((res)=> {
                //     this.essayList=res.data
                //     console.log(res.data)
                // })
                console.log(`当前页: ${val}`);
            },
            //分页方法
            currentChangePage(list, currentPage) {
                let from = (currentPage - 1) * this.pageNum;
                let to = currentPage * this.pageNum;
                this.tempList = [];
                for (; from < to; from++) {
                    if (list[from]) {
                        this.tempList.push(list[from]);
                    }
                }
            },


//===================复选框获取选中id并加入数组==================
            handleSelectionChange(val) {
                for (var i = 0; i < val.length; i++) {
                    this.deleteIdList.push(val[i].adId)
                }
                this.multipleSelection = this.deleteIdList;
                this.deleteIdList = []
            },
            //修改方法
            handleClick(row) {
                sessionStorage.setItem('arr', JSON.stringify(row))
                this.$router.push({name: 'updateAdvertisement'})
                console.log(row);
            },
            deleteRow(adId, rows) {
//=============================发起单个删除请求将得到的ad_id 传到后台=========================================================
                // this.$axios.post('/api/',{ad_id:ad_id})
                this.id = adId
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //发起单个删除请求传出id  liekai yigeyemianwugeqingqiu
                    this.$axios.post('/api/ad/delete', [this.id]).then((res) => {
                        console.log(res.data)//打印数据
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.$axios.post('/api/ad/adlist?page=' + this.currentPage1).then((res) => {
                            this.adList = res.data.data
                            //分页
                            this.total = res.data.count
                        })
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '删除失败'
                        });
                    });
                    console.log(this.id)
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
                console.log(adId)
            },
            //批量删除广告的方法
            toggleSelection() {
//=======================================发起批量删除申请 将选中的id数组传给后台===============================================
                console.log(this.multipleSelection)
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //发起批量删除 删除请求
                    console.log(this.multipleSelection)
                    this.$axios.post('/api/ad/delete', [...this.multipleSelection]).then((res) => {
                        this.$axios.post('/api/ad/adlist?page=' + this.currentPage1).then((res) => {
                            this.adList = res.data.data
                            //分页
                            this.total = res.data.count
                        })
                        //提示用户删除成功
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },


//    =============================添加=======================
            uploadFile(file) {
                console.log(file)
                this.formData.append('file', file.file);
            },
            handleChange(file, fileList) {
                this.fileList = fileList;
            },
            //创建submit提交请求创建
            submitForm(addAdArr) {
                //构造formData
                let formData = new FormData()
                console.log(this.fileList)
                formData.append('file', this.fileList[0].raw)


                this.$refs[addAdArr].validate((valid) => {
                    if (valid) {
                        this.$axios({
                            method: 'post',
                            url: '/api/ad/add',
                            params: {
                                adName: this.addAdArr.adName,
                                adUrl: this.addAdArr.adUrl,
                                adStatus: this.addAdArr.adStatus
                            },
                            data: formData
                        }).then((res) => {
                            console.log(res)
                            this.activeName='first'
                        }).catch((err) => {
                            console.log(err)
                        })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            //重置按钮
            resetForm(addAdArr) {
                this.$refs.addAdArr.resetFields()
            },
            //删除图标的方法
            handleRemove(file) {
                this.$refs.pictureUpload.uploadFiles = []
            },
            //预览
            handlePictureCardPreview(file) {
                this.addAdArr.file = file.url;
                this.dialogVisible = true;
            },
            //下载方法
            handleDownload(file) {
                console.log(file);
            },
            getGoodsId() {
                this.$axios.post('/api/goods/list', {
                    goodsName: this.addAdArr.adName,
                    goodsType: null,
                    goodsUuid: null,
                }).then((res) => {
                    console.log(res.data.data)
                        this.zhi = res.data.data
                })

            },
        },
        data(){
            return{
                zhi:[],
                adList:[
                    {
                        adStatus:'0'
                    }
                ],
                input:'',
                deleteIdList:[],
                activeName: 'first', //tabs默认选择first
                startTime: {
                    startTime: '2021/01/03'
                },
// ======================分页=========================
            currentPage1: 1,//默认在第一页
                page:'1',
                total:5,//默认总条数
                pageNum:5,//每页显示条数,
                tempList:[],

//===================================添加=================================================
                addAdArr: {
                    adName:'',//广告名称
                    adUrl:'',//广告链接
                    file:'',//广告图片
                    adStatus:'1',//广告显示状态
                    ad_is_deleted:'',//是否删除
                    ad_sort:'',//广告排序
                    ad_create_time:'',//创建时间
                    ad_update_time:''
                },
                fileList:[],
                rules:{
                    adName: [
                        { required: true, message: '请输入广告名称', trigger: 'blur' },
                        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
                    ],
                    ad_create_time: [
                        { type: 'date', required: true, message: '请选择开始日期', trigger: 'change' }
                    ],
                    ad_update_time: [
                        { type: 'date', required: true, message: '请选择结束日期', trigger: 'change' }
                    ],
                    ad_sort:[{
                        required: true, message: '请填写广告排序', trigger: 'blur'}],
                    adStatus: [
                        { required: true, message: '请选择是否开启广告', trigger: 'change' }
                    ],
                    adUrl: [
                        { required: true, message: '请填写广告链接', trigger: 'blur' }
                    ]
                },
                dialogVisible: false,
                disabled: false,
                file:'',
            }
        },
        created() {
            this.$axios.post('/api/ad/adlist').then((res)=> {
            this.adList=res.data.data
                //分页
                this.total=res.data.count
            })
        }
    }
</script>

<style scoped>
    .delete{
        float: left;
    }
    /*.el-input{*/
    /*    width: 150px;*/
    /*}*/
    .select-div{
        float: left;
        padding-left: 20px;
    }
    .select{
        margin-left: 20px;
    }
    .el-tabs{
        height: 560px;
    }
    .el-form{
        width: 40%;
        overflow: hidden;
        padding-left: 20px;
    }
    .el-form-item{
        text-align: left;
    }
</style>